package com.acme.javaschool.sems.ionio.serialization.impl;

import com.acme.javaschool.sems.ionio.serialization.SensorData;
import com.acme.javaschool.sems.ionio.serialization.Serializer;
import com.acme.javaschool.sems.ionio.serialization.protobuf.SensorDataPb;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ProtobufSerializer implements Serializer<SensorData> {

    @Override
    public void serialize(OutputStream outputStream, SensorData object) {

        SensorDataPb.SensorData message = SensorDataPb.SensorData.newBuilder()
                .setElevation(object.getElevation())
                .setLatitude(object.getLatitude())
                .setLongitude(object.getLongitude())
                .setTemperature(object.getTemperature())
                .build();

        try {
            message.writeDelimitedTo(outputStream);
            outputStream.flush();
        } catch (IOException e) { e.printStackTrace(); }
    }

    @Override
    public SensorData deserialize(InputStream inputStream) {

        try {
            SensorDataPb.SensorData message = SensorDataPb.SensorData.parseDelimitedFrom(inputStream);

            return new SensorData(
                    message.getLongitude(),
                    message.getLatitude(),
                    message.getElevation(),
                    message.getTemperature()
            );

        } catch (IOException e) { e.printStackTrace(); }

        return null;
    }
}
